
/// 使用 Uint8List 数据类型
import 'dart:typed_data';

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
/// 使用 DefaultCacheManager 类（可能无法自动引入，需要手动引入）
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

/// 授权管理
// import 'package:permission_handler/permission_handler.dart';
/// 图片缓存管理
import 'package:cached_network_image/cached_network_image.dart';
/// 保存文件或图片到本地
import 'package:image_gallery_saver/image_gallery_saver.dart';

class AppUtil {
  /// 保存图片到相册
  ///
  /// 默认为下载网络图片，如需下载资源图片，需要指定 [isAsset] 为 `true`。
  static Future<void> saveImage(String imageUrl, {bool isAsset: false}) async {
    EasyLoading.show(status: '保存中...');
    try {

      if (imageUrl == null){
        EasyLoading.showToast('保存失败，图片不存在！');
        return;
      }
      /// 权限检测
      // PermissionStatus storageStatus = await Permission.storage.status;
      // if (storageStatus != PermissionStatus.granted) {
      //   storageStatus = await Permission.storage.request();
      //   if (storageStatus != PermissionStatus.granted) {
      //     EasyLoading.showToast('无法存储图片，请先授权！');
      //     return;
      //   }
      // }

      /// 保存的图片数据
      Uint8List imageBytes;

      if (isAsset == true) {
        /// 保存资源图片
        ByteData bytes = await rootBundle.load(imageUrl);
        imageBytes = bytes.buffer.asUint8List();
      } else {
        var response = await Dio().get(imageUrl, options: Options(responseType: ResponseType.bytes));
        imageBytes = Uint8List.fromList(response.data);
      }
      /// 保存图片
      final result = await ImageGallerySaver.saveImage(imageBytes);

      if(ObjectUtil.isEmpty(result)){
        EasyLoading.showToast('保存失败');
      }else{
        EasyLoading.showToast('保存成功');
      }
    } catch (e) {
      EasyLoading.showToast('保存失败');
    }
  }

  /// 保存ByteData图片到相册
  static Future<void> saveByteImage(Uint8List imageBytes) async {
    EasyLoading.show(status: '保存中...');
    try {

      // if (imageBytes == null){
      //   EasyLoading.showToast('保存失败，图片不存在！');
      //   return;
      // }
      /// 权限检测
      // PermissionStatus storageStatus = await Permission.storage.status;
      // if (storageStatus != PermissionStatus.granted) {
      //   storageStatus = await Permission.storage.request();
      //   if (storageStatus != PermissionStatus.granted) {
      //     EasyLoading.showToast('无法存储图片，请先授权！');
      //     return;
      //   }
      // }
      /// 保存图片
      final result = await ImageGallerySaver.saveImage(imageBytes);
      print("图片地址------${result}");
      if(ObjectUtil.isEmpty(result)){
        EasyLoading.showToast('保存失败');
      }else{
        EasyLoading.showToast('保存成功');
      }
    } catch (e) {
      EasyLoading.showToast('保存失败');
    }
  }

}